﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace _01Lock
{
    class Program
    {
        private static readonly object _syncRoot = new Object();
        static Thread t1 = new Thread(new ParameterizedThreadStart(P));
        static Thread t2 = new Thread(new ParameterizedThreadStart(P));
        static Thread t3 = new Thread(new ParameterizedThreadStart(P));
        static void Main(string[] args)
        {
            t1.Name = "A";
            t2.Name = "B";
            t3.Name = "C";

            t1.Start(t1);
            t2.Start(t2);
            t3.Start(t3);
            //t1.Join();
            //t2.Join();
            //t3.Join();
            //Console.WriteLine("------------");
            //Console.ReadKey();
        }

        static void P(object name)
        {
            Thread t = name as Thread;
            Console.WriteLine("线程名:{0}-1 占用资源\t时间:{5:HH:mm:ss.fff}  当前线程:{1,-18} A:{2,-18} B:{3,-18} C:{4}",
                t.Name, t.ThreadState.ToString() + " ID:" + t.ManagedThreadId,t1.ThreadState.ToString() + " ID:" + t1.ManagedThreadId,
                t2.ThreadState.ToString() + " ID:" + t2.ManagedThreadId,t3.ThreadState.ToString() + " ID:" + t3.ManagedThreadId,
                DateTime.Now);
            lock (_syncRoot)
            {
                Console.WriteLine("线程名:{0}-2 Sleep前\t时间:{5:HH:mm:ss.fff}  当前线程:{1,-18} A:{2,-18} B:{3,-18} C:{4}",
                    t.Name, t.ThreadState.ToString() + " ID:" + t.ManagedThreadId,t1.ThreadState.ToString() + " ID:" + t1.ManagedThreadId,
                    t2.ThreadState.ToString() + " ID:" + t2.ManagedThreadId,t3.ThreadState.ToString() + " ID:" + t3.ManagedThreadId,
                    DateTime.Now);
                Thread.Sleep(5000);
                Console.WriteLine("线程名:{0}-3 Sleep后\t时间:{5:HH:mm:ss.fff}  当前线程:{1,-18} A:{2,-18} B:{3,-18} C:{4}",
                    t.Name, t.ThreadState.ToString() + " ID:" + t.ManagedThreadId,t1.ThreadState.ToString() + " ID:" + t1.ManagedThreadId,
                    t2.ThreadState.ToString() + " ID:" + t2.ManagedThreadId,t3.ThreadState.ToString() + " ID:" + t3.ManagedThreadId,
                    DateTime.Now);
            }
            Console.WriteLine("线程名:{0}-4 释放资源\t时间:{5:HH:mm:ss.fff}  当前线程:{1,-18} A:{2,-18} B:{3,-18} C:{4}",
                t.Name, t.ThreadState.ToString() + " ID:" + t.ManagedThreadId,t1.ThreadState.ToString() + " ID:" + t1.ManagedThreadId,
                t2.ThreadState.ToString() + " ID:" + t2.ManagedThreadId,t3.ThreadState.ToString() + " ID:" + t3.ManagedThreadId,
                DateTime.Now);
        }
    }
}
